document.addEventListener('DOMContentLoaded', function() {
    // DOM 元素
    const treeContainer = document.getElementById('tree-container');
    const addRootBtn = document.getElementById('add-root');
    const searchInput = document.getElementById('search');
    const editorModal = document.getElementById('editor-modal');
    const editTitle = document.getElementById('edit-title');
    const editContent = document.getElementById('edit-content');
    const saveEditBtn = document.getElementById('save-edit');
    const cancelEditBtn = document.getElementById('cancel-edit');
	
	// 在DOM元素获取部分添加导出按钮的引用
const exportBtn = document.getElementById('export-btn');
const importBtn = document.getElementById('import-btn');

const batchDeleteBtn = document.getElementById('batch-delete');

// 递归设置子节点的选中状态
function setChildrenChecked(item, checked) {
    item.isChecked = checked;
    if (item.children && item.children.length > 0) {
        item.children.forEach(child => setChildrenChecked(child, checked));
    }
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkedItems = getCheckedItems(items);
    batchDeleteBtn.disabled = checkedItems.length === 0;
    batchDeleteBtn.textContent = `批量删除 (${checkedItems.length})`;
}

// 获取所有选中的项目
function getCheckedItems(itemsList, result = []) {
    itemsList.forEach(item => {
        if (item.isChecked) {
            result.push(item);
        }
        if (item.children && item.children.length > 0) {
            getCheckedItems(item.children, result);
        }
    });
    return result;
}

// 批量删除选中项目
function batchDelete() {
    const checkedItems = getCheckedItems(items);
    if (checkedItems.length === 0) return;
    
    if (confirm(`确定要删除选中的 ${checkedItems.length} 个项目吗？`)) {
        checkedItems.forEach(item => {
            const parent = findParent(items, item.id);
            removeItemFromParent(item, parent || items);
        });
        renderTree();
    }
}




// 添加导出数据函数
function exportData() {
    const data = JSON.stringify(items, null, 2); // 格式化JSON
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `checklist-${new Date().toISOString().slice(0,10)}.json`; // 使用日期作为文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 添加导入数据函数
function importData(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const importedItems = JSON.parse(e.target.result);
            if (Array.isArray(importedItems)) {
                items = importedItems;
                renderTree();
                alert('数据导入成功！');
            } else {
                alert('导入失败：文件格式不正确');
            }
        } catch (error) {
            alert('导入失败：文件解析错误');
            console.error(error);
        }
    };
    reader.readAsText(file);
    
    // 重置input，以便可以重复导入同一文件
    event.target.value = '';
}

// 在事件监听部分添加导出导入的事件监听
exportBtn.addEventListener('click', exportData);
importBtn.addEventListener('change', importData);
	

    // 从本地存储加载数据或使用默认数据
    let items = loadFromLocalStorage() || [
        {
            id: '1',
            title: '工作项目',
            content: '',
            children: [
                {
                    id: '1-1',
                    title: '开发任务',
                    content: '完成前端页面开发',
                    children: [
                        { id: '1-1-1', title: '登录页面', content: '实现登录功能', children: [] },
                        { id: '1-1-2', title: '仪表盘', content: '设计数据展示', children: [] }
                    ]
                },
                { id: '1-2', title: '会议', content: '周例会', children: [] }
            ]
        },
        {
            id: '2',
            title: '个人计划',
            content: '',
            children: [
                { id: '2-1', title: '学习', content: '学习新技能', children: [] },
                { id: '2-2', title: '健身', content: '每周三次', children: [] }
            ]
        }
    ];

    // 当前编辑的项目
    let currentEditItem = null;
    let currentParent = null;

    // 生成唯一ID
    function generateId() {
        return Math.random().toString(36).substr(2, 9);
    }
	
	  // 保存数据到本地存储
    function saveToLocalStorage(data) {
        try {
            localStorage.setItem('infinite-checklist', JSON.stringify(data));
        } catch (e) {
            console.error('保存到本地存储失败:', e);
            // 处理存储空间不足的情况
            if (e.name === 'QuotaExceededError') {
                alert('本地存储空间不足，请删除一些数据');
            }
        }
    }

    // 从本地存储加载数据
    function loadFromLocalStorage() {
        try {
            const data = localStorage.getItem('infinite-checklist');
            return data ? JSON.parse(data) : null;
        } catch (e) {
            console.error('从本地存储加载数据失败:', e);
            return null;
        }
    }
	
	
	

    // 渲染清单树并保存到本地存储
  function renderTree(itemsToRender = items) {
	   console.log('Rendering tree with items:', itemsToRender);
    _renderTree(itemsToRender);
    updateBatchDeleteButton(); // 每次渲染后更新批量删除按钮状态
    saveToLocalStorage(items);
}


    // 实际渲染树的内部函数
function _renderTree(itemsToRender, parent = null, level = 0) {
    // 只在顶层清空容器
    if (level === 0) {
        treeContainer.innerHTML = '';
    }
    
    itemsToRender.forEach(item => {
        const node = renderTreeNode(item, parent, level);
        if (level === 0) {
            treeContainer.appendChild(node);
        }
        
        // 只在renderTreeNode中处理子节点渲染
    });
}

    // 渲染单个树节点
    function renderTreeNode(item, parent, level) {
    const node = document.createElement('div');
    node.className = 'tree-node';
    node.dataset.id = item.id;
    
    const header = document.createElement('div');
    header.className = 'node-header';
    header.draggable = true;
    
    // 添加复选框
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.className = 'node-checkbox';
    checkbox.checked = item.isChecked || false;
    checkbox.onchange = (e) => {
        const isChecked = e.target.checked;
        item.isChecked = isChecked;
        if (item.children && item.children.length > 0) {
            setChildrenChecked(item, isChecked);
        }
        updateBatchDeleteButton();
        header.classList.toggle('checked', isChecked);
        renderTree();
    };
    header.appendChild(checkbox);
    
    // 展开/折叠图标
    const expandIcon = document.createElement('span');
    expandIcon.className = 'expand-icon';
    expandIcon.textContent = item.children.length > 0 ? (item.isExpanded !== false ? '▼' : '►') : ' ';
    expandIcon.onclick = () => toggleExpand(item);
    header.appendChild(expandIcon);
    
    // 标题和内容容器
    const titleContentContainer = document.createElement('div');
    titleContentContainer.className = 'title-content-container';
    
    // 标题
    const titleSpan = document.createElement('span');
    titleSpan.className = 'node-title';
    titleSpan.textContent = item.title;
    titleContentContainer.appendChild(titleSpan);
    
    // 添加分隔线和内容
    if (item.content) {
        // 分隔线
        const separator = document.createElement('span');
        separator.className = 'separator';
        separator.textContent = ' ---- ';
        titleContentContainer.appendChild(separator);
        
        // 内容预览
        const contentPreview = document.createElement('span');
        contentPreview.className = 'content-preview';
        
        // 处理内容显示逻辑
        if (item.content.length > 30) {  // 超过30字符显示...
            contentPreview.textContent = item.content.substring(0, 30) + '...';
            contentPreview.title = item.content; // 添加tooltip显示完整内容
            contentPreview.onclick = (e) => {
                e.stopPropagation();
                // 点击展开/收起完整内容
                if (contentPreview.textContent.endsWith('...')) {
                    contentPreview.textContent = item.content;
                } else {
                    contentPreview.textContent = item.content.substring(0, 30) + '...';
                }
            };
        } else {
            contentPreview.textContent = item.content;
        }
        
        titleContentContainer.appendChild(contentPreview);
    }
    
    header.appendChild(titleContentContainer);
    
    // 操作按钮
    const actions = document.createElement('div');
    actions.className = 'node-actions';
    
    const addBtn = document.createElement('button');
    addBtn.textContent = '+';
    addBtn.onclick = (e) => {
        e.stopPropagation();
        addChildItem(item);
    };
    
    const editBtn = document.createElement('button');
    editBtn.textContent = '✏️';
    editBtn.onclick = (e) => {
        e.stopPropagation();
        editItem(item);
    };
    
    const deleteBtn = document.createElement('button');
    deleteBtn.textContent = '🗑️';
    deleteBtn.onclick = (e) => {
        e.stopPropagation();
        deleteItem(item, parent || items);
    };
    
    actions.appendChild(addBtn);
    actions.appendChild(editBtn);
    actions.appendChild(deleteBtn);
    header.appendChild(actions);
    
    node.appendChild(header);
    
    // 子节点容器
    if (item.children && item.children.length > 0 && item.isExpanded !== false) {
        const childrenContainer = document.createElement('div');
        childrenContainer.className = 'node-children';
        
        item.children.forEach(child => {
            childrenContainer.appendChild(renderTreeNode(child, item, level + 1));
        });
        
        node.appendChild(childrenContainer);
    }
    
    return node;
}

    // 查找项目
    function findItem(items, id) {
        for (const item of items) {
            if (item.id === id) return item;
            if (item.children && item.children.length > 0) {
                const found = findItem(item.children, id);
                if (found) return found;
            }
        }
        return null;
    }

    // 查找父项目
    function findParent(items, id, parent = null) {
        for (const item of items) {
            if (item.id === id) return parent;
            if (item.children && item.children.length > 0) {
                const found = findParent(item.children, id, item);
                if (found) return found;
            }
        }
        return null;
    }

    // 从父项目中移除项目
    function removeItemFromParent(item, parent) {
        if (Array.isArray(parent)) {
            // 根项目
            const index = parent.findIndex(i => i.id === item.id);
            if (index !== -1) parent.splice(index, 1);
        } else if (parent && parent.children) {
            const index = parent.children.findIndex(i => i.id === item.id);
            if (index !== -1) parent.children.splice(index, 1);
        }
    }

    // 切换展开/折叠
       function toggleExpand(item) {
        item.isExpanded = !item.isExpanded;
        renderTree(); // 自动保存
    }


    // 添加根项目
    function addRootItem() {
        currentEditItem = {
            id: generateId(),
            title: '',
            content: '',
            children: []
        };
        currentParent = items;
        showEditor('新建根项目');
    }

    // 添加子项目
    function addChildItem(parent) {
        currentEditItem = {
            id: generateId(),
            title: '',
            content: '',
            children: []
        };
        currentParent = parent;
        showEditor('新建子项目');
    }

    // 编辑项目
    function editItem(item) {
        currentEditItem = item;
        currentParent = null;
        showEditor('编辑项目');
    }

    // 删除项目
      function deleteItem(item, parent) {
        if (confirm(`确定要删除 "${item.title}" 吗？`)) {
            removeItemFromParent(item, parent);
            renderTree(); // 自动保存
        }
    }

    // 显示编辑器
    function showEditor(title) {
        document.getElementById('editor-title').textContent = title;
        editTitle.value = currentEditItem.title;
        editContent.value = currentEditItem.content;
        editorModal.style.display = 'flex';
    }

    // 隐藏编辑器
    function hideEditor() {
        editorModal.style.display = 'none';
    }

    // 保存编辑
        function saveItem() {
        currentEditItem.title = editTitle.value;
        currentEditItem.content = editContent.value;
        
        if (currentParent) {
            if (Array.isArray(currentParent)) {
                // 添加到根
                currentParent.push(currentEditItem);
            } else {
                // 添加到子
                if (!currentParent.children) currentParent.children = [];
                currentParent.children.push(currentEditItem);
            }
        }
        
        hideEditor();
        renderTree(); // 自动保存
    }

    // 搜索功能
    function searchItems() {
        const term = searchInput.value.toLowerCase();
        if (!term) {
            renderTree(items);
			 updateBatchDeleteButton(); // 搜索后更新按钮状态
            return;
        }
        
        function filterItems(items, term) {
            return items.filter(item => {
                const matches = item.title.toLowerCase().includes(term) || 
                              item.content.toLowerCase().includes(term);
                
                if (item.children && item.children.length > 0) {
                    item.children = filterItems(item.children, term);
                    return matches || item.children.length > 0;
                }
                
                return matches;
            });
        }
        
        const filtered = filterItems(JSON.parse(JSON.stringify(items)), term);
        renderTree(filtered);
    }


function toggleAllItems(checked) {
    function setChecked(itemsList) {
        itemsList.forEach(item => {
            item.isChecked = checked;
            if (item.children && item.children.length > 0) {
                setChecked(item.children);
            }
        });
    }
    
    setChecked(items);
    renderTree();
}

document.getElementById('select-all').addEventListener('click', () => toggleAllItems(true));
document.getElementById('deselect-all').addEventListener('click', () => toggleAllItems(false));
    // 事件监听
   
	
	addRootBtn.addEventListener('click', addRootItem);
saveEditBtn.addEventListener('click', saveItem);
cancelEditBtn.addEventListener('click', hideEditor);
searchInput.addEventListener('input', searchItems);
exportBtn.addEventListener('click', exportData);
importBtn.addEventListener('change', importData);
batchDeleteBtn.addEventListener('click', batchDelete);

// 初始渲染
renderTree();

 
});